<?php
// +----------------------------------------------------------------------
// | Description: 基础类，无需验证权限。
// +----------------------------------------------------------------------
// | Author:
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\User;
use app\common\Constants\ErrorCode;
use com\verify\HonrayVerify;
use app\common\controller\Common;
use Excel\Excel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Session;
use think\Request;
use think\facade\Db;
use think\response\Json;


class Base extends Common
{

    /**
     * 后台用户登录
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author ran
     * @date 2021-09-15 14:06
     * mailbox 466180170@qq.com
     */
    public function login()
    {
        $param = $this->param;
        $userModel = new User();
        $username = $param['username'] ?? '';
        $password = $param['password'] ?? '';
        $type = $param['type'] ?? 1;
        $res = $userModel->login($username, $password,(int)$type);
        if (!$res) {
            return  $this->failed(ErrorCode::SYSTEM_INVALID,$userModel->getError());
        }
        Session::set('user_id', $res['userInfo']['id']);
        return  $this->success($res);
    }
    /**
     * 退出登录
     * @return Json
     * @author Mr.Li
     * @create 2021-06-05 11:44
     */
    public function logout()
    {

        $request = $this->request;
        // $param = $this->param;
        $header = $request->header();
        $param = $request->param();
        if(empty($param['id'])){
            return resultArray(['error' => '请输入用户id']);
        }

        $header['auth_key'] = isset($header['auth-key']) && $header['auth-key'] ? trim($header['auth-key']) : '';
        if(!Cache::handler()){
            return resultArray(['error' => '请使用redis作为缓存']);
        }
        try {
            $cache = Cache::delete('auth:'.$header['auth_key']);
            Cache::handler()->srem('authUser:'.$param['id'],$header['auth_key']);
            session('user_id','null');
        }catch (\Exception $e) {
            return resultArray(['error'=>'退出失败']);
        }
        return resultArray(['data'=>[],'error'=>'退出成功']);
    }



    /**
     * 获取图片验证码
     * @return \think\Response|Json
     * @author Mr.Li longfei
     * @create 2021-05-24 10:35
     */
    public function getVerify()
    {
        //$param['type'] 1 登录 2忘记密码
        $param = $this->param;
        if(empty($param['type'])){
            return resultArray(['error' => '请输入验证码类型']);
        }
        $captcha = new HonrayVerify(config('captcha'));
        $base64 = 'data:image/png;base64,' . base64_encode($captcha->entry($param['type'])->getData());
        return resultArray(['data' => $base64]);
    }


    /**
     * 发送短信验证码
     * @return Json
     * @author Mr.Li
     * @create 2021-06-05 11:44
     */
    public function sendTpSms()
    {

        $param = input();
        if (empty($param['mobile'])) return resultArray(['error' => '请输入手机号！']);
        $userModel = new User();
        $userInfo = $userModel->getDataByMobile($param['mobile']);
        if (!$userInfo) {
            //$this->error = '密码没改变';
            return resultArray(['error' => $userModel->getError()]);
        }
        $tpSmsObj = send_tp_sms(1,1);
        if(!$tpSmsObj->getErrorMsg()){
            return resultArray(['data' =>['code' => $tpSmsObj->getCode()] ]);
        }
        return resultArray(['error' => $tpSmsObj->getErrorMsg()]);


    }

    //网站信息
    public function index()
    {
        $systemModel = model('System');
        $data = $systemModel->getDataList();
        return  resultArray(['data' => $data]);
    }

    // miss 路由：处理没有匹配到的路由规则
    public function miss()
    {
        if (Request::instance()->isOptions()) {
            return ;
        } else {
            echo '逮虾记';
        }
    }

    /**
     * 导入测试
     * @author zl
     */
    public function excel_import()
    {
        $table  = 'shop_goods';
        $fields = [];
        // $file 导入文件, $table = null, $fields = null, $type = 0, $where = null, $main_field = null
        $result = Excel::first_import($_FILES['file'], $table, $fields, 0, null, 'goods_no');
        if ($result['error'] == 0) {
            return resultArray(['data' => []]);
        } else {
            return resultArray(['error' => $result['message']]);
        }
    }

    /**
     * 获取网站备案号
     * @author Zl
     */
    public function websiteRecord()
    {
        $webRecord = Db::name('admin_setting')->where('name', 'website_record')->value('value');
        return resultArray(['data' => $webRecord, 'error'=> '获取成功']);
    }


    /**
     * 处理区域
     * @author Mr.Li
     * @create 2021-06-09 9:54
     */

    public function operateRegion()
    {

        exit();

        /*
       $regionData = Db::name('shop_region2')->select()->toArray();
       $province = $city = $town = [];
       if($regionData){
           foreach($regionData as $item){
               if(!isset($province[$item['proviceCode']])){
                   $province[$item['proviceCode']] = [
                       'name'      => $item['proviceame'],
                       'level'     => 1,
                       'code'      => $item['proviceCode'],
                       'parent_id' => 0,
                   ];
               }

               if(!isset($city[$item['cityCode']])){
                   $city[$item['cityCode']] = [
                       'name'      => $item['cityame'],
                       'level'     => 2,
                       'code'      => $item['cityCode'],
                       'parent_id' => 0,
                   ];
               }

               if(!isset($town[$item['areaCode']])){
                   $town[$item['areaCode']] = [
                       'name'      => $item['areaame'],
                       'level'     => 3,
                       'code'      => $item['areaCode'],
                       'parent_id' => 0,
                   ];
               }

           }
       }

       if($province){
           Db::name('shop_region3')->insertAll(array_values($province));
       }
       if($city){
           Db::name('shop_region3')->insertAll(array_values($city));
       }
       if($town){
           Db::name('shop_region3')->insertAll(array_values($town));
       }

       print_r(1);
       die;
       */
        //得到所有的等级是2

        $towns = Db::name('shop_region3')->where('level','=',3)->where('id','>',2443)->select()->toArray();

        //更新城市上级
        /*
         $citys = Db::name('shop_region3')->where('level','=',2)->select()->toArray();
        if($citys){
            $cityCodes = array_column($citys,'code');
            $provinceCodes = Db::name('shop_region2')->where('cityCode','in',$cityCodes)->column('proviceCode','cityCode');
            $provinces = Db::name('shop_region3')->where('code','in',array_unique(array_values($provinceCodes)))->column('id','code');
            foreach($citys as $cityItem)
            {
                $pcode = $provinceCodes[$cityItem['code']] ?? '';
                 if(!$pcode){
                     print_r($cityItem);
                 }
                Db::name('shop_region3')->where('id','=',$cityItem['id'])->update(['parent_id' => $provinces[$pcode]]);
            }
        }
        */
        // 更新区县上级

        try{
            if($towns){
                $townCodes = array_column($towns,'code');
                $cityCodes = Db::name('shop_region2')->where('areaCode','in',$townCodes)->column('cityCode','areaCode');
                $cityCodees = Db::name('shop_region3')->where('code','in',array_unique(array_values($cityCodes)))->column('id','code');
                foreach($towns as $toenItem)
                {
                    $citycode = $cityCodes[$toenItem['code']] ?? '';
                    if(!$citycode){
                        continue;
                    }
                    Db::name('shop_region3')->where('id','=',$toenItem['id'])->update(['parent_id' => $cityCodees[$citycode]]);
                }

            }
        }catch (\Exception $e) {

            print_r($e->getMessage());

            exit();

        }


        print_r(1);
        die;


    }
}
